<?php
/**
 * PhotoController.php
 *
 * 用户相册控制器
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://momoger.com/license
 *
 * @category	Home
 * @package		Home_Controller
 * @author 		Leo
 * @version    	1.0
 * @copyright  	Copyright © 2009 www.momoger.com All Rights Reserved.
 * @license    	http://momoger.com/license     New BSD License
 */

/** Momoger_Controller_Public */
//require_once 'Momoger/Controller/Public.php';

/**
 * 相册 分类 控制器
 *
 * @category	Home
 * @package		Home_Controller
 * @copyright  	Copyright © 2009 www.momoger.com All Rights Reserved.
 * @license    	http://momoger.com/license     New BSD License
 */
class PhotoController extends Momoger_Controller_Public {

	/**
	 * 控制器初始化
	 *
	 * @return void
	 */
	public function mmInit() {

	}

	/**
	 * 相册列表默认接口
	 *
	 * @return HTML
	 */
	public function indexAction() {
		$this->view->nav = 'photo';
		$this->view->userID = (int)$this->getRequest()->getParam('user_id');
	}

	/**
	 * 显示一组图片
	 *
	 * @return HTML
	 */
	public function viewAction() {
		//the photo id
		$photoID = (int)$this->getRequest()->getParam('photo_id');

		$photo = new Momoger_Model_Photo();
		$viewPhoto = $photo->getPhoto($photoID);
		if (!$viewPhoto['photoID']) {
			$this->redirectWithMsg(3, 'The Photo is invalid!', NULL, '/');
			return FALSE;
		}
		$viewPhoto['imgViewUri'] = $viewPhoto['userID'] . '/' . date('Ym', $viewPhoto['photoCreated']) . '/600x400/' . $viewPhoto['photoID'] . '.png';

		$cacheKey = 'homePhotoViewCategory' . $viewPhoto['categoryID'];
		$photos = $this->cache()->get($cacheKey);
		if (!$photos) {
			$rows = $photo->getPhotos(0, $viewPhoto['categoryID'], 'photoID ASC', 100);
			$photos = array();
			foreach ($rows as $row) {
				$row['imgViewUri'] = $row['userID'] . '/' . date('Ym', $row['photoCreated']) . '/600x400/' . $row['photoID'] . '.png';
				$photos[$row['photoID']] = $row;
			}
			$this->cache()->set($cacheKey, $photos);
			$this->logger()->debug('Update cache by key: ' . $cacheKey);
		}

		if (!array_key_exists($photoID, $photos)) {
			$photos[$photoID] = $viewPhoto;
		}

		$this->view->nav = 'photo';
		$this->view->photoID = $photoID;
		$this->view->photoDomain = 'http://upload.momoger.com/photo/';
		$this->view->photos = $photos;

		return TRUE;
	}

	/**
	 * 相册缩略图列表接口
	 *
	 * 使用缓存支持
	 *
	 * @return HTML
	 */
	public function thumbAction() {
		// close layout
		if (null !== ($layout = Zend_Layout::getMvcInstance())) {
            $layout->disableLayout();
        }

		//the category id, if setted
		$categoryID = (int)$this->getRequest()->getParam('category_id');

		//the page number, if setted
		$cpage = (int)$this->getRequest()->getParam('cpage', 1);
		$pageSize = 16;

		//the cache key
		$cacheKey = 'homePhotoThumbByCategoryID' . $categoryID . 'AndPage' . $cpage;

		//the cache tags
		$cacheTags = array('homePhotoThumbByCategory', 'homePhotoThumbByCategoryID' . $categoryID);

		//get cache by key
		$photos = $this->cache()->get($cacheKey);
		if (!$photos) {
			$photos = array();
			if ($categoryID) {
				$category = new Momoger_Model_Category();
				$row = $category->getCategory($categoryID);
				$photos['totalPhotos'] = (int)$row['categoryCounts'];
				$photos['category'] = $row;

				$user = new Momoger_Model_User();
				$photos['owner'] = $user->getUser($row['userID']);
			} else {
				$profile = new Momoger_Model_Profile();
				$theProfile = $profile->getProfile(Momoger_Model_Profile::TOTAL_PHOTO_NUMBER);
				$photos['totalPhotos'] = $theProfile['pValue'];
			}

			$photo = new Momoger_Model_Photo();
			$photos['photos'] = $photo->getPhotos(NULL, $categoryID, array('photoID DESC'), $pageSize, $pageSize * ($cpage - 1));

			$this->cache()->set($cacheKey, $photos, $cacheTags);

			$this->logger()->debug('Update cache by key: ' . $cacheKey);
		}

		$this->view->pageSize = $pageSize;
		$this->view->currentPage = $cpage;
		$this->view->recordCount = $photos['totalPhotos'];
		$this->view->photoDomain = 'http://upload.momoger.com/photo/';
		$this->view->photos = $photos;
	}

	/**
	 * 相册分类显示接口
	 *
	 * 使用缓存支持
	 *
	 * @return HTML
	 */
	public function categoryAction() {
		// close layout
		if (null !== ($layout = Zend_Layout::getMvcInstance())) {
            $layout->disableLayout();
        }

		//the user id, if special view user category
		$userID = (int)$this->getRequest()->getParam('user_id');

		//the cache key
		$cacheKey = 'homePhotoCategoriesByUserID' . $userID;

		//the cache tags
		$cacheTags = array('homePhotoCategories');

		//get cache by key
		$categories = $this->cache()->get($cacheKey);
		if (!$categories) {
			//get data from model
			$category = new Momoger_Model_Category();
			$categories = $category->getCategoriesForPublic($userID, 'photo', 100);
			$this->cache()->set($cacheKey, $categories, $cacheTags);
			$this->logger()->debug('Update cache by key: ' . $cacheKey);
		}

		//set the data to view
		$this->view->categories = $categories;
	}

	/**
	 * 用户图片缩略图列表
	 *
	 * @return HTML
	 */
	public function listAction() {
		// close layout
		if (null !== ($layout = Zend_Layout::getMvcInstance())) {
            $layout->disableLayout();
        }

        //the photo category id
		$categoryID = (int)$this->getRequest()->getParam('category_id');

		$cpage = (int)$this->getRequest()->getParam('cpage', 1);
		$pageSize = 20;
		$totalPhotos = 0;

		$this->view->category = array();

		$category = new Momoger_Model_Category();
		if ($categoryID) {
			$row = $category->getCategory($categoryID);
			$totalPhotos = (int)$row['categoryCounts'];
			$this->view->category = $row;
		} else {
			$totalPhotos = $this->user->userPhotos;
		}

		$this->view->categories = $category->getCategories($this->user->userID, 'photo');

		$photo = new Momoger_Model_Photo();
		$photos = $photo->getPhotos($this->user->userID, $categoryID, array('photoID DESC'), $pageSize, $pageSize * ($cpage - 1));

		$this->view->pageSize = $pageSize;
		$this->view->currentPage = $cpage;
		$this->view->recordCount = $totalPhotos;
		$this->view->photoDomain = 'http://upload.momoger.com/photo/';
		$this->view->photos = $photos;
	}

	/**
	 * save edit photo information
	 *
	 * @return JSON
	 */
	public function editedAction() {
		// close layout
		if (null !== ($layout = Zend_Layout::getMvcInstance())) {
            $layout->disableLayout();
        }

        //get params
        $photoID = (int)$this->getRequest()->getParam('photo_id');
        $categoryID = (int)$this->getRequest()->getParam('category_id');

        $filter = new Zend_Filter_StripTags();
		$title = $filter->filter($this->getRequest()->getParam('title'));
		$desc = $filter->filter($this->getRequest()->getParam('desc'));

		$photo = new Momoger_Model_Photo();
		$oldData = $photo->getPhoto($photoID);

		$jsonRs = array('result' => false, 'msg' => 'Invalid Photo ID: ' . $photoID);

		if (!isset($oldData['photoID']) || !$oldData['photoID']) {
			$this->getHelper('Json')->sendJson($jsonRs);
			return $jsonRs['result'];
		}

		if ($oldData['userID'] != $this->user->userID) {
			$jsonRs['msg'] = 'You can not edit the photo. It is not yours!';
			$this->getHelper('Json')->sendJson($jsonRs);
			return $jsonRs['result'];
		}

		$photo->set(array('categoryID' => $categoryID, 'photoTitle' => $title, 'photoDesc' => $desc))->save();

		if ($categoryID != $oldData['categoryID']) {
			$category = new Momoger_Model_Category();
			$category->find($categoryID);
			$category->set(array('categoryCounts' => $category->get('categoryCounts') + 1, 'categoryUpdated' => time()))->save();
			$category->reset()->find($oldData['categoryID']);
			$category->set(array('categoryCounts' => $category->get('categoryCounts') - 1, 'categoryUpdated' => time()))->save();
		}

		$jsonRs['msg'] = 'The photo ' . $title . ' data updated success!';
		$jsonRs['result'] = true;
		$this->getHelper('Json')->sendJson($jsonRs);
		return $jsonRs['result'];
	}

	/**
	 * delete photo
	 *
	 * @return JSON
	 */
	public function deleteAction() {
		// close layout
		if (null !== ($layout = Zend_Layout::getMvcInstance())) {
            $layout->disableLayout();
        }

        $photoID = (int)$this->getRequest()->getParam('photo_id');
        $photo = new Momoger_Model_Photo();
        $delPhoto = $photo->getPhoto($photoID);

		$jsonRs = array('result' => false, 'msg' => 'Invalid Photo ID: ' . $photoID);

		if (!isset($delPhoto['photoID']) || !$delPhoto['photoID']) {
			$this->getHelper('Json')->sendJson($jsonRs);
			return $jsonRs['result'];
		}

		if ($delPhoto['userID'] != $this->user->userID) {
			$jsonRs['msg'] = 'You can not delete the photo. It is not yours!';
			$this->getHelper('Json')->sendJson($jsonRs);
			return $jsonRs['result'];
		}

		//delete disk file
		$files = array(
			'original/' . $delPhoto['photoID'] . '.' . $delPhoto['photoType'],
			'600x400/' . $delPhoto['photoID'] . '.png',
			'120x80/' . $delPhoto['photoID'] . '.png'
		);
		foreach ($files as $file) {
			@unlink(UPLOAD_DIR . '/photo/' . $delPhoto['userID'] . '/' . date('Ym', $delPhoto['photoCreated']) . '/' . $file);
		}

		//update information
		$this->user->userPhotos -= 1;
		$user = new Momoger_Model_User();
		$user->find($delPhoto['userID']);
		$user->set('userPhotos', $user->get('userPhotos') - 1)->save();

		$category = new Momoger_Model_Category();
		$category->find($delPhoto['categoryID']);
		$category->set(array('categoryCounts' => $category->get('categoryCounts') - 1))->save();

		$profile = new Momoger_Model_Profile();
		$profile->find('upload_photo_number');
		$profile->set(array('pValue' => $profile->get('pValue') - 1))->save();

		//delete photo records
		$photo->delete();

		$jsonRs['msg'] = 'The photo ' . $delPhoto['photoTitle'] . ' has been deleted!';
		$jsonRs['result'] = true;
		$this->getHelper('Json')->sendJson($jsonRs);
		return $jsonRs['result'];
	}

	/**
	 * 添加新的 分类信息
	 *
	 * @return JSON
	 */
	public function addAction() {
		// close layout
		if (null !== ($layout = Zend_Layout::getMvcInstance())) {
            $layout->disableLayout();
        }

        //init the upload max size
        $uploadMaxSize = substr(ini_get('upload_max_filesize'), 0, -1) * 1024;

        //get use exists categories
		$category = new Momoger_Model_Category();
		$this->view->categories = $category->getCategories($this->user->userID, 'photo');

		//set max upload size
		$this->view->maxSize = $uploadMaxSize;
	}

	/**
	 * 保存用户上传的图片，
	 * 保留一份用户上传的原图。
	 * 制作一份 600X400 的缩放图
	 * 制作一份 120X80 的缩放图
	 *
	 * @return HTML
	 */
	public function uploadAction() {

		//image may be very .....
		set_time_limit(0);

		// close layout
		if (null !== ($layout = Zend_Layout::getMvcInstance())) {
            $layout->disableLayout();
        }

		//no view render
		$this->_helper->viewRenderer->setNoRender();

		//init the upload max size
        $uploadMaxSize = substr(ini_get('upload_max_filesize'), 0, -1) * 1024;

		//user auth validate
		if(!$this->user || !(int)$this->user->userID) {
			//set reponse data
			$this->uploaded(0, 'Invalid user!');

			//log it
			$this->logger()->debug('upload invalid: Invalid user!');

			return FALSE;
		}

		//php server memory limit
		$phpMemLimit = substr(ini_get('memory_limit'), 0, -1);
		if ($phpMemLimit < 16) {
			//set reponse data
			$this->uploaded(0, 'Server limit php memory too litter! can not build new image!');

			//log it
			$this->logger()->debug('Server limit php memory too litter! can not build new image!');

			return FALSE;
		}

		//photo category id
		$categoryID = (int)$this->getRequest()->getParam('category_id');

		// upload class
		$upload = new App_Util_Upload('upfile', $uploadMaxSize * 1024, array('png','jpg', 'gif'));

		// invalid upload option
		if (!$upload->isValid()) {
			//set reponse data
			$this->uploaded(0, $upload->getErrorMsg());

			//log it
			$this->logger()->debug('upload invalid: ' . $upload->getErrorMsg());

			return FALSE;
		}

		//get photo name
		//$user = new Momoger_Model_User($this->user);
		//$photoID = $user->photo()->set('categoryID', $categoryID)->save();
		$photo = new Momoger_Model_Photo();
		$photoID = $photo->set(array('userID' => $this->user->userID, 'categoryID' => $categoryID))->save()->get('photoID');

		//photo name get false
		if (!$photoID) {
			//set reponse data
			$this->uploaded(0, 'Sorry! The photo can not get a name!');

			//log it
			$this->logger()->debug('upload invalid: Sorry! The photo can not get a name!');

			return FALSE;
		}

		//update photo data
		//$user->photo()->set('photoID', $photoID);

		//set the photo new name
		$photoName = $photoID . '.' . $upload->getExtName();

		//set the photo save dir
		$photoUri = UPLOAD_DIR . '/photo/' . $this->user->userID . '/' . date('Ym') . '/original/' . $photoName;

		//save photo
		if (!$upload->save($photoUri)) {

			//save false
			$photo->delete();

			//set reponse data
			$this->uploaded(0, $upload->getErrorMsg());

			//log it
			$this->logger()->debug('save false: ' . $upload->getErrorMsg());

			return FALSE;
		}

		//get saved photo information
		$photoInfo = $upload->getUploadFileInfo();

		$filter = new Zend_Filter_StripTags();
		$title = $filter->filter($this->getRequest()->getParam('title'));
		$desc = $filter->filter($this->getRequest()->getParam('desc'));
		if (!$title) {
			$title = $photoInfo['name'];
		} else {
			if (function_exists('mb_substr')) {
				$title = mb_substr($title, 0, 100);
			} else {
				$title = substr($title, 0, 100);
			}
		}
		if (!$desc) {
			$desc = $photoInfo['name'];
		}

		//update photo model data
		$photo->set(array(
			'photoCreated' => time(),
			'photoName' => $photoInfo['name'],
			'photoType' => $photoInfo['suffix'],
			'photoSize' => $photoInfo['size'],
			'photoTitle' => $title,
			'photoDesc'	=> $desc
		));

		//new iamge size define
		$viewPhotoWidth = 600;
		$viewPhotoHeight = 400;
		$thumbPhotoWidth = 120;
		$thumbPhotoHeight = 80;

		//new zoomed image type
		$newPhotoType = 'png';

		//zoom photo to new size
		$newPhotoDir = UPLOAD_DIR . '/photo/' . $this->user->userID . '/' . date('Ym') . '/' . $viewPhotoWidth . 'x' . $viewPhotoHeight;

		//check the new zoomed imaged save dir
		if (!is_dir($newPhotoDir)) {
			if (!mkdir($newPhotoDir, 0755)) {
				@unlink($photoUri);
				$photo->delete();
				$this->uploaded(0, 'Create image save path false!');
				$this->logger()->err('Create image save path false: ' . $newPhotoDir);
				return FALSE;
			}
		}

		//set the new zoomed image save uri
		$newPhotoUri = $newPhotoDir . '/' . $photoID . '.' . $newPhotoType;

		//create image object
		$img = new App_Util_Image($photoUri, $newPhotoUri, $newPhotoType, $viewPhotoWidth, $viewPhotoHeight);

		//add water mark to new image, postion is bottom, right
		$img->setWaterImage(UPLOAD_DIR . '/momogerwater.png', 3);

		//zoome image
		if(!$img->zoomImage()) {
			@unlink($photoUri);
			$photo->delete();
			$this->uploaded(0, $img->getMsg());
			$this->logger()->err('Create new image false: ' . $newPhotoUri . $img->getMsg());
			return FALSE;
		}
		unset($img);

		//create the thumb image file. set the save dir
		$thumbPhotoDir = UPLOAD_DIR . '/photo/' .  $this->user->userID . '/' . date('Ym') . '/' . $thumbPhotoWidth . 'x' . $thumbPhotoHeight;

		//check the dir
		if (!is_dir($thumbPhotoDir)) {
			if (!mkdir($thumbPhotoDir, 0755)) {
				@unlink($photoUri);
				@unlink($newPhotoUri);
				$photo->delete();
				$this->uploaded(0, 'Create image thumb save path false!');
				$this->logger()->err('Create image thumb save path false: ' . $thumbPhotoDir);
				return FALSE;
			}
		}

		//set the thumb image file save uri
		$thumbPhotoUri = $thumbPhotoDir . '/' . $photoID . '.' . $newPhotoType;

		//create image object
		$img = new App_Util_Image($photoUri, $thumbPhotoUri, $newPhotoType, $thumbPhotoWidth, $thumbPhotoHeight);

		//create thumb image file
		if(!$img->zoomImage()) {
			@unlink($photoUri);
			@unlink($newPhotoUri);
			$photo->delete();
			$this->uploaded(0, $img->getMsg());
			$this->logger()->err('Create new image false: ' . $newPhotoUri . $img->getMsg());
			return FALSE;
		}
		unset($img);

		//save model data
		$photo->save();

		//update relation information
		$user = new Momoger_Model_User();
		$user->addNewSuccess($this->user->userID, $categoryID, 'photo');
		$this->user->userPhotos += 1;

		//reponse client
		$this->uploaded(1, 'Congratulations! New photo saved success!');
		return TRUE;
	}

	/**
	 * 图片上传结果处理
	 *
	 * @param int $result 处理结果 1 or 0
	 * @param string $msg 详细信息
	 */
	private function uploaded($result, $msg) {
		echo <<< HereDoc
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Uploaded</title>
<script type="text/javascript">
<!--
window.onload = function() {
	var uploadRs = $result;
	var msg = '$msg';
	var uploadBoxObj = parent.document.getElementById("user-body-box");
	uploadBoxObj.uploaded(msg, uploadRs);
};
//-->
</script>
</head>
<body>
</body>
</html>
HereDoc;
	}
}